package com.sdutcm.xuake.xuanke_demo.service;

import com.sdutcm.xuake.xuanke_demo.bean.XuanKe;
import com.sdutcm.xuake.xuanke_demo.dao.CourseDao;
import com.sdutcm.xuake.xuanke_demo.dao.XuanKeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2018-09-20 00:51
 * @package com.sdutcm.xuake.xuanke_demo.service
 * @description
 */
@Service
@Transactional
public class XuanKeService {
    @Autowired
    CourseDao courseDao;
    @Autowired
    XuanKeDao xuanKeDao;


    //选课
    public boolean xuanKe(int xuehao,String kechengming) throws Exception {

        if (getByXuehaoAndKeMing(xuehao,kechengming)!=null){
            throw new Exception();
        }
        courseDao.decrYvLiang(kechengming);
        XuanKe xuanKe=new XuanKe();
        xuanKe.setDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        xuanKe.setXuehao(xuehao);
        xuanKe.setKechengming(kechengming);
        xuanKeDao.save(xuanKe);
        return true;

    }

    //退课
    public boolean tuiKe(int xuehao,String kechengming){
        try {
            courseDao.incrYvLiang(kechengming);
            xuanKeDao.deleteByXuehaoAndKechengming(xuehao,kechengming);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public XuanKe getByXuehaoAndKeMing(int xuehao,String kechengming) {
        return xuanKeDao.findByXuehaoAndAndKechengming(xuehao,kechengming);
    }


}
